package jvs.sh.cmd;

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * 
 * @author qiangli
 *
 */
public class FileUploader {

	public static void post(String file, String type, URL url, String[][] nvps) throws IOException {
		final String boundary = Long.toHexString(System.currentTimeMillis());
		FileInputStream is = null;
		DataOutputStream os = null;
		try {
			HttpURLConnection.setFollowRedirects(true);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setAllowUserInteraction(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Close"); //
			conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
		
			is = new FileInputStream(file);
			os = new DataOutputStream(conn.getOutputStream());
			//
			os.writeBytes("--" + boundary + "\r\n");
			//
			for (int i = 0; i < nvps.length; i++) {
				String n = nvps[i][0];
				String v = nvps[i][1];
				os.writeBytes("Content-Disposition: form-data; name=\""+n+"\"\r\n");   
				os.writeBytes("\r\n"+v+"\r\n");
				os.writeBytes("--" + boundary + "\r\n");
			}
			//
			os.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + file + "\"\r\n");
			type = (type == null ? URLConnection.guessContentTypeFromName(file) : type);
			os.writeBytes("Content-Type: " + type +"\r\n");
			//os.writeBytes("Content-Transfer-Encoding: binary\r\n");
			os.writeBytes("\r\n");
			os.flush();
			byte[] buf = new byte[1024];
			while (true) {
				int read = is.read(buf);
				if (read == -1) {
					break;
				}
				os.write(buf, 0, read);
			}
			os.flush();
		
			os.writeBytes("\r\n--" + boundary + "--\r\n");
			os.flush();
		} finally {
			if (is != null) {
				is.close();
			}
			if (os != null) {
				os.close();
			}
		}
	}
	
	public static void main(String[] args) {
		try {
			String postback = "/_ah/upload/ahdob3R3ZWJhZ2VudC5hcHBzcG90LmNvbXIbCxIVX19CbG9iVXBsb2FkU2Vzc2lvbl9fGCAM";
			URL url = new URL("http://localhost:8888" + postback);
			String name = "name betty";
			String peer = "peer@gmail.com";
			String uri = "content://abcd/content/pkg";
			String access = "3";
			String[][] nvps = new String[][]{{"name", name}, {"peer", peer}, {"uri", uri}, {"access", access}};
			post("c:/temp/image.png", "image/png", url, nvps);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
